package com.rayson.oneapi.config;

import com.rayson.oneapi.common.R;
import com.rayson.oneapi.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * Author: rayson
 * Description:
 * Version: 1.0
 * Date: 2024-09-02 23:27
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionAdvice {


    @ExceptionHandler(BusinessException.class)
    public R<Void> businessExceptionHandler(BusinessException exception) {
        return R.error(exception.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<Void> MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        ObjectError objectError = e.getAllErrors().get(0);
        return R.error(objectError.getDefaultMessage());
    }

    @ExceptionHandler(Exception.class)
    public R<Void> exceptionHandler(Exception exception) {
        log.error(exception.getMessage(), exception);
        return R.error("系统异常");
    }
}
